home *** CD-ROM | disk | FTP | other *** search
/ Java Developer's Companion / Java Developer's Companion.iso / Javacup / PR8ADPL7.TAR / productivity_tools / PR8ADPL7 / PrinterDevice.java < prev    next >
Encoding:
Java Source  |  1996-05-23  |  1.6 KB  |  62 lines

  1. // PrinterDevice
  2. // Write data to a printer accessible from the machine the JFS server
  3. // is running on. All printers are listed in the file /etc/printers, and
  4. // have the format
  5. //
  6. // PRINTER = Name ':' TYPE ':' Description ':' Command
  7. //
  8. // TYPE = 'Postscript' | 'Text' | 'PPM'
  9. //
  10. import java.io.*;
  11.  
  12. public class PrinterDevice extends DeviceDriver
  13. {
  14.     // write
  15.     // Valid message parameters are:
  16.     //  Printer: <name>    // must be in /etc/printers
  17.     void write(Message msg, ServerClient s) throws IOException
  18.     {
  19.     String printer = msg.find("Printer");
  20.     if (printer == null)
  21.         throw new IOException("No Printer given");
  22.  
  23.     // Read /etc/printers
  24.     BufferInputStream pfile = null;
  25.     try pfile = new BufferInputStream(
  26.              FileSystem.getfile("/etc/printers",0,-1,-1));
  27.     catch(BadPathException e)
  28.         throw new IOException("Couldn't read /etc/printers");
  29.  
  30.     // Find the print command for this printer
  31.     String command = null;
  32.     while(true) {
  33.         String line = null;
  34.         try line = pfile.gets();
  35.         catch(IOException e)
  36.             throw new IOException("Printer "+printer+" not found");
  37.         StringSplitter tok = new StringSplitter(line,':');
  38.         if (tok.countTokens() != 4)
  39.             continue;    // bogus line
  40.         if (tok.nextToken().equals(printer)) {
  41.             tok.nextToken();
  42.             tok.nextToken();
  43.             command = tok.nextToken();
  44.             break;
  45.             }
  46.         }
  47.  
  48.     // Run the print command, feeding it the data to be printed
  49.     try {
  50.         String cmdarr[] = { "/bin/sh", "-c", command };
  51.         Process proc = Runtime.getRuntime().exec(cmdarr);
  52.         proc.getOutputStream().write(msg.getdata());
  53.         proc.getOutputStream().close();
  54.         proc.waitFor();
  55.         }
  56.     catch(Exception e)
  57.         throw new IOException("Error running print command "+
  58.                       command);
  59.     }
  60. }
  61.  
  62.